import { Server } from 'socket.io'
import { userList } from './socketList'
export default class socketSever {
  private io
  constructor(sereve) {
    this.io = new Server(sereve)
    this.io.on('connection', (socket) => {
      socket.on('message', (msg) => {
        this.io.emit('message', {
          id: socket.id,
          msg
        })
      })
      socket.on('disconnect', () => {
        userList.delete(socket.id)
        this.userListChange()
      })
      socket.on('upLine', (userId) => {
        if (userList.has(socket.id)) {
          userList.get(userId).userId = userId
        } else {
          userList.set(userId, { socket, userId })
        }
        this.userListChange()
      })
    })
    return this
  }
  userListChange = () => {
    const onlineUserIds = [];
    userList.forEach(item => {
      onlineUserIds.push({
        userId: item.userId,
        socketId: item.socket.id
      })
    })
    this.io.emit('userListChange', {
      onlineUserIds
    })
  }
}
